//
//  AuctionCouponVC.m
//  MyNewProject
//
//  Created by 王春辉 on 2020/1/5.
//  Copyright © 2020年 sun. All rights reserved.
//

#import "AuctionCouponVC.h"
#import "ClassifySectionCell.h"
#import "ProductDetailVC.h"

#pragma mark -- mark 数据相关
#import "AuctionNewUserEnjoyModel.h"
#import "AuctionCoponListModel.h"

#define MARGIN 15.0

@interface AuctionCouponVC ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout> {
    int _page;
}
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSArray <AuctionNewUserEnjoyDataModel *>* dataArray;
@property (nonatomic, strong) NSArray <AuctionCouponModel *>* couponArray;
@end
static NSString *const identifier = @"cell_identifier";
@implementation AuctionCouponVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.gk_navTitle = @"新人专享";
    self.view.backgroundColor = SKColorWithHex(0xF7F7F7);
    [self initContentViews];
}
- (void)initContentViews {
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.mas_offset(SKTopBar_Height);
        make.bottom.mas_offset(-SKBottomSafe_Height);
    }];
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestNewGoodsList)];
    self.collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestMoreNewGoodsList)];
    [self requestNewUserCouponList];
    [self requestNewGoodsList];
}

- (void)addHeaderView {
    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = [UIColor whiteColor];
    [self.collectionView addSubview:headerView];
    UIImageView *headerImageView = [[UIImageView alloc] initWithImage:SKIMAGE_NAMED(@"auction_new_user_header_img")];
    headerImageView.contentMode = UIViewContentModeScaleAspectFit;
    [headerView addSubview:headerImageView];
    [headerImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_offset(0);
    }];
    
    UILabel *label = [[UILabel alloc] init];
    label.text = @"-新人专享券-";
    label.textColor = SKColorWithHex(0x333333);
    label.font = SKFONT_BOLD_SIZE(18);
    [headerView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_offset(0);
        make.top.mas_equalTo(headerImageView.mas_bottom).mas_offset(40);
        make.height.mas_equalTo(19);
    }];
    
    UILabel *label1 = [[UILabel alloc] init];
    label1.text = @"(优惠券仅限新人特惠使用)";
    label1.font = SKFONT_SIZE(13);
    label1.textColor = SKColorWithHex(0xB1B1B1);
    [headerView addSubview:label1];
    [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_offset(0);
        make.top.mas_equalTo(label.mas_bottom).mas_offset(6);
        make.height.mas_equalTo(14);
    }];
    
    CGFloat m = 6;
    CGFloat w = (self.view.width - MARGIN * 2 - m) * 0.5;
    CGFloat h = w / 171.0 * 70;
    UIView *lastView;
    for (int i = 0; i < self.couponArray.count; i++) {
        AuctionCouponModel *model = self.couponArray[i];
        AuctionCouponView *view = [[AuctionCouponView alloc] init];
        [headerView addSubview:view];
        view.money = model.money;
        view.limit = model.tiaojian;
        view.able = !model.is_have;
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(MARGIN + (i % 2) * (w + m));
            make.top.mas_equalTo(label1.mas_bottom).mas_offset(20 + (i / 2) * (h + m));
            make.size.mas_equalTo(CGSizeMake(w, h));
        }];
        lastView = view;
    }
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"一键领取" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.titleLabel.font = SKFONT_BOLD_SIZE(18);
    button.backgroundColor = SKColorWithHex(0xF9962E);
    button.layer.masksToBounds = true;
    button.layer.cornerRadius = 38.0 * 0.5;
    [button addTarget:self action:@selector(getAllCouponsButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:button];
    
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(MARGIN);
        make.right.mas_offset(-MARGIN);
        make.top.mas_equalTo(lastView.mas_bottom).mas_offset(20);
        make.bottom.mas_offset(-20);
    }];
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_offset(0);
        make.width.mas_equalTo(self.view);
    }];
    self.headerView = headerView;
    [self.collectionView reloadData];
}

#pragma mark -- mark 懒加载
/*
- (UIView *)headerView {
    if (!_headerView) {
        _headerView = [[UIView alloc] init];
        _headerView.backgroundColor = [UIColor whiteColor];
        [self.collectionView addSubview:_headerView];
        UIImageView *headerImageView = [[UIImageView alloc] initWithImage:SKIMAGE_NAMED(@"auction_new_user_header_img")];
        headerImageView.contentMode = UIViewContentModeScaleAspectFit;
        [_headerView addSubview:headerImageView];
        [headerImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.mas_offset(0);
        }];
        
        UILabel *label = [[UILabel alloc] init];
        label.text = @"-新人专享券-";
        label.textColor = SKColorWithHex(0x333333);
        label.font = SKFONT_BOLD_SIZE(18);
        [_headerView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_offset(0);
            make.top.mas_equalTo(headerImageView.mas_bottom).mas_offset(40);
            make.height.mas_equalTo(19);
        }];
        
        UILabel *label1 = [[UILabel alloc] init];
        label1.text = @"(优惠券仅限新人特惠使用)";
        label1.font = SKFONT_SIZE(13);
        label1.textColor = SKColorWithHex(0xB1B1B1);
        [_headerView addSubview:label1];
        [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_offset(0);
            make.top.mas_equalTo(label.mas_bottom).mas_offset(6);
            make.height.mas_equalTo(14);
        }];
        
        AuctionCouponView *view1 = [[AuctionCouponView alloc] init];
        AuctionCouponView *view2 = [[AuctionCouponView alloc] init];
        AuctionCouponView *view3 = [[AuctionCouponView alloc] init];
        AuctionCouponView *view4 = [[AuctionCouponView alloc] init];
        [_headerView addSubview:view1];
        [_headerView addSubview:view2];
        [_headerView addSubview:view3];
        [_headerView addSubview:view4];
        [view1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(15);
            make.right.mas_equalTo(view2.mas_left).mas_offset(-6);
            make.top.mas_equalTo(label1.mas_bottom).mas_offset(20);
            make.bottom.mas_equalTo(view3.mas_top).mas_offset(-6);
            make.height.mas_equalTo(view1.mas_width).multipliedBy(70.0/171);
            make.size.mas_equalTo(view2);
            make.size.mas_equalTo(view3);
            make.size.mas_equalTo(view4);
        }];
        [view2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_offset(-15);
            make.top.bottom.mas_equalTo(view1);
        }];
        [view3 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(view1);
        }];
        [view4 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(view2);
            make.top.mas_equalTo(view3);
        }];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"一键领取" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.titleLabel.font = SKFONT_BOLD_SIZE(18);
        button.backgroundColor = SKColorWithHex(0xF9962E);
        button.layer.masksToBounds = true;
        button.layer.cornerRadius = 38.0 * 0.5;
        [button addTarget:self action:@selector(getAllCouponsButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_headerView addSubview:button];
        
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(view1);
            make.right.mas_equalTo(view2);
            make.top.mas_equalTo(view3.mas_bottom).mas_offset(20);
            make.bottom.mas_offset(-20);
        }];
    }
    return _headerView;
}
 */
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        CGFloat centerMargin = 5.0; // 中间边距
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat item_w = (self.view.width - MARGIN * 2 - centerMargin) * 0.5;
        CGFloat item_h = item_w / 170.0 * 228.0;
        layout.itemSize = CGSizeMake(item_w, item_h);
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.minimumLineSpacing = 5;
        layout.minimumInteritemSpacing = 5;
        layout.sectionInset = UIEdgeInsetsMake(0, MARGIN, MARGIN, MARGIN);
        self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        [_collectionView registerClass:[ClassifySectionCell class] forCellWithReuseIdentifier:identifier];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsHorizontalScrollIndicator = false;
        _collectionView.backgroundColor = self.view.backgroundColor;
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}



#pragma mark -- mark UICollectionViewDelegate UICollectionViewDataSource

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SKWeakSelf;
    AuctionNewUserEnjoyDataModel *model = self.dataArray[indexPath.item];
    ClassifySectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    cell.title = model.name;
    cell.price = model.price;
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.img] placeholderImage:SKIMAGE_NAMED(@"cell_default_img")];
    cell.shareButtonClickBlock = ^{
        [weakSelf cellShareButtonClickWith:indexPath];
    };
    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self showProductDetailWith:indexPath];
}

#pragma mark -- mark UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return self.headerView.size;
}


#pragma mark -- mark 获取网络数据

- (void)requestNewUserCouponList {
    if (!(self.uid && self.loginKey)) {
        [self endRefreshing];
        return;
    }
    SKWeakSelf;
    NSDictionary *param = @{@"uid":self.uid,
                            @"loginKey":self.loginKey,
                            @"type":@(1) // 1新人2普通
                            };
    [YQNetworking getWithUrl:@"Shop/shopCouponList" params:param reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        AuctionCoponListModel *model = [AuctionCoponListModel modelWithDictionary:response];
        if ([model isSuccess]) {
            weakSelf.couponArray = model.data;
            [weakSelf addHeaderView];
        }else { }
        [weakSelf endRefreshing];
    } failBlock:^(NSError *error) {
        [weakSelf endRefreshing];
        [weakSelf debugShowMessage:error.localizedDescription];
    }];
}


- (void)requestNewGoodsList {
    _page = 1;
    SKWeakSelf;
    [self requestNewGoodsListWith:_page Complete:^(NSArray<AuctionNewUserEnjoyDataModel *> *data) {
        weakSelf.dataArray = data;
        [weakSelf.collectionView reloadData];
    }];
}
- (void)requestMoreNewGoodsList {
    if (_page == 0) {
        [self endRefreshing];
        return; }
    _page += 1;
    SKWeakSelf;
    [self requestNewGoodsListWith:_page Complete:^(NSArray<AuctionNewUserEnjoyDataModel *> *data) {
        NSMutableArray *mArr = [NSMutableArray arrayWithArray:weakSelf.dataArray];
        [mArr addObjectsFromArray:data];
        weakSelf.dataArray = mArr;
        [weakSelf.collectionView reloadData];
    }];
}
- (void)requestNewGoodsListWith:(int)page Complete:(void(^)(NSArray <AuctionNewUserEnjoyDataModel *>*))complete {
    SKWeakSelf;
    [YQNetworking getWithUrl:@"Shop/getNewGoodsList" params:@{@"page":@(page)} reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        AuctionNewUserEnjoyModel *model = [AuctionNewUserEnjoyModel modelWithDictionary:response];
        if ([model isSuccess]) {
            if (complete) {
                complete(model.data);
            }
        }else {
            [weakSelf showMessage:model.msg];
        }
        [weakSelf endRefreshing];
    } failBlock:^(NSError *error) {
        [weakSelf endRefreshing];
        [weakSelf debugShowMessage:error.localizedDescription];
    }];
}

- (void)endRefreshing {
    if ([self.collectionView.mj_header isRefreshing]) {
        [self.collectionView.mj_header endRefreshing];
    }
    if ([self.collectionView.mj_footer isRefreshing]) {
        [self.collectionView.mj_footer endRefreshing];
    }
}

/**
 一键领取
 */
- (void)getAllCoupons {
    if (!(self.uid && self.loginKey)) {
        [self endRefreshing];
        return; }
    SKWeakSelf;
    NSMutableString *ids = [NSMutableString string];
    for (AuctionCouponModel *model in self.couponArray) {
        if (!model.is_have) {
            [ids appendString:model.ID];
            [ids appendString:@","];
        }
    }
    if (ids.length > 2) {
        [ids deleteCharactersInRange:NSMakeRange(ids.length - 1, 1)];
    }
    NSDictionary *param = @{@"uid":@([self.uid intValue]),
                            @"loginKey":self.loginKey,
                            @"ids":ids
                            };
    [YQNetworking getWithUrl:@"Shop/setShopCouponAll" params:param reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        WJBaseModel *model = [WJBaseModel modelWithDictionary:response];
        if ([model isSuccess]) {
            [weakSelf requestNewUserCouponList];
            [weakSelf showMessage:model.msg];
        }else {
            if ([model.msg containsString:@"失败"]) {
                [weakSelf showMessage:@"已经领取过了"];
            }else {
                [weakSelf showMessage:model.msg];
            }
        }
    } failBlock:^(NSError *error) {
        [weakSelf debugShowMessage:error.localizedDescription];
    }];
}
#pragma mark -- mark EVENT

/**
 点击领取优惠券

 @param sender sender
 */
- (void)couponButtonClick:(UIButton *)sender {
    
}

/**
 一键领取

 @param sender sender
 */
- (void)getAllCouponsButtonClick:(UIButton *)sender {
    [self getAllCoupons];
}

#pragma mark -- mark 业务逻辑

/**
 查看商品详情
 
 @param indexPath indexPath
 */
- (void)showProductDetailWith:(NSIndexPath *)indexPath {
    AuctionNewUserEnjoyDataModel *model = self.dataArray[indexPath.item];
    if (model.ID.length > 0) {
        ProductDetailVC *vc = [[ProductDetailVC alloc] init];
        vc.type = 0;
        vc.ptId = model.ID;
        vc.showType = ProductDetailTypeDetail;
        [self.navigationController pushViewController:vc animated:YES];
    }else {
        [self showMessage:@"无效的数据信息"];
    }
}
/**
 分享商品
 
 @param indexPath indexPath
 */
- (void)cellShareButtonClickWith:(NSIndexPath *)indexPath {
    
}
@end

#pragma mark -- mark 优惠券view
@interface AuctionCouponView()

/**
 金额
 */
@property (nonatomic, strong) UILabel *moneyLabel;

/**
 使用限制
 */
@property (nonatomic, strong) UILabel *limitLabel;
@end
@implementation AuctionCouponView
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        UIImageView *imageView = [[UIImageView alloc] initWithImage:SKIMAGE_NAMED(@"auction_copon_bg_img")];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.layer.masksToBounds = true;
        [self addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(self);
        }];
        UILabel *yuan = [[UILabel alloc] init];
        yuan.text = @"¥";
        yuan.font = SKFONT_BOLD_SIZE(13);
        yuan.textColor = [UIColor whiteColor];
        [self addSubview:yuan];
        [yuan mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(self.moneyLabel).mas_offset(-4);
            make.right.mas_equalTo(self.moneyLabel.mas_left).mas_offset(-4);
        }];
        [self.moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_offset(0);
            make.right.mas_equalTo(self.mas_centerX).mas_offset(-10);
        }];
        UIView *line = [[UIView alloc] init];
        line.backgroundColor = SKRGBAColor(255, 255, 255, 0);
        [self addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.mas_offset(0);
            make.top.mas_offset(16);
            make.width.mas_offset(0.5);
        }];
        
        UILabel *label = [[UILabel alloc] init];
        label.textColor = [UIColor whiteColor];
        label.textAlignment = NSTextAlignmentCenter;
        label.text = @"优惠券";
        label.font = SKFONT_BOLD_SIZE(13);
        [self addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(line.mas_right).mas_offset(4);
            make.right.mas_offset(-4);
            make.bottom.mas_equalTo(self.mas_centerY).mas_offset(-4);
        }];
        [self.limitLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(label);
            make.top.mas_equalTo(label.mas_bottom).mas_offset(8);
        }];
        UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
        gesture.numberOfTapsRequired = 1;
        [self addGestureRecognizer:gesture];
    }
    return self;
}
- (void)setAble:(BOOL)able {
    _able = able;
    self.layer.opacity = able ? 1 : 0.6;
    self.userInteractionEnabled = !able;
}
- (void)setMoney:(NSString *)money {
    _money = money;
    self.moneyLabel.text = money;
}
- (void)setLimit:(NSString *)limit {
    _limit = limit;
    self.limitLabel.text = [NSString stringWithFormat:@"满%@可用", limit];
}
#pragma mark -- mark 懒加载
- (UILabel *)moneyLabel {
    if (!_moneyLabel) {
        _moneyLabel = [[UILabel alloc] init];
        _moneyLabel.textColor = [UIColor whiteColor];
        _moneyLabel.font = SKFONT_BOLD_SIZE(30);
        _moneyLabel.text = @" ";
        [self addSubview:_moneyLabel];
    }
    return _moneyLabel;
}
- (UILabel *)limitLabel {
    if (!_limitLabel) {
        _limitLabel = [[UILabel alloc] init];
        _limitLabel.text = @" ";
        _limitLabel.font = SKFONT_Medium(11);
        _limitLabel.textAlignment = NSTextAlignmentCenter;
        _limitLabel.textColor = SKRGBAColor(255, 255, 255, 0.6);
        [self addSubview:_limitLabel];
    }
    return _limitLabel;
}

#pragma mark -- mark EVENT

- (void)tapGesture:(UITapGestureRecognizer *)sender {
    if (self.getCouponTapBlock) {
        self.getCouponTapBlock();}
}
@end
